<template>
  <div>
    <upload-excel-component
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    />
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { formatExcelDate } from '@/utils/index.js'
import { importEmployee } from '@/api/employees.js'

export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },

    async handleSuccess({ results, header }) {
      console.log('读出来的excel的内容是', results, header)
      this.tableData = results
      this.tableHeader = header

      const newData = this.transExcel(results, header)
      console.log('结果', newData)

      await importEmployee(newData)
      this.$message.success('导入成功')
      this.$router.push('/employees')
    },
    transExcel(results, header) {
      const mapInfo = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName',
        聘用形式: 'formOfEmployment'
      }
      return results.map((item) => {
        // 保存新数据
        const obj = {}
        header.forEach((element) => {
          // obj的key = mapInfo的value
          // 同时在将results的value取来赋给obj，组成新的对象
          const k = mapInfo[element]
          if (k === 'timeOfEntry' || k === 'correctionTime') {
            obj[k] = new Date(formatExcelDate(item[element]))
          } else {
            obj[k] = item[element]
          }
        })
        // 返回
        return obj
      })
    }
  }
}
</script>
